//
//  OYTextBarrageView.m
//  ZhiXingLiPlus
//
//  Created by 掌游网络 on 2017/10/18.
//  Copyright © 2017年 wwtech. All rights reserved.
//

#import "OYTextBarrageView.h"

@interface OYTextBarrageView () {
    
    NSInteger _textIndex;
    UILabel *_contentLabel;
}

@property (nonatomic, strong) CADisplayLink *displayLink;

@end

@implementation OYTextBarrageView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.clipsToBounds = YES;
        _textIndex = 0;
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    _contentLabel.oy_centerY = self.oy_height / 2.0;
}

#pragma mark - 添加文字
- (void)setTextArr:(NSArray *)textArr {
    _textArr = textArr;
    
    [_contentLabel removeFromSuperview];
    _contentLabel = [[UILabel alloc] init];
    _contentLabel.textColor = OYRGBFrom16(0x353535);
    _contentLabel.font = [UIFont systemFontOfSize:14];
    _contentLabel.text = textArr.firstObject;
    [_contentLabel sizeToFit];
    [self addSubview:_contentLabel];
    _contentLabel.oy_x = self.oy_width;
    
    [self.displayLink invalidate];
    self.displayLink = nil;
    [self addTimer];
}

#pragma mark - 绘制移动
- (void)labelMove {
    
    if (_contentLabel.oy_right < 0) {
        _textIndex ++;
        if (_textIndex == self.textArr.count) {
            _textIndex = 0;
        }
        _contentLabel.text = self.textArr[_textIndex];
        [_contentLabel sizeToFit];
        _contentLabel.oy_x = self.oy_width;
    }
    
    _contentLabel.oy_x -= 1.5;
}

#pragma mark - 添加定时器
- (void)addTimer {
    if (self.displayLink) {
        return;
    }
    // 每秒执行60次回调
    CADisplayLink *link = [CADisplayLink displayLinkWithTarget:self selector:@selector(labelMove)];
    // 将定时器添加到runLoop
    [link addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
    self.displayLink = link;
}

#pragma mark - lazy load


@end
